package com.sunday.shoufen.ui;

import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.flyco.tablayout.SlidingTabLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.AppBarStateChangeListener;
import com.sunday.common.widgets.banner.ConvenientBanner;
import com.sunday.common.widgets.banner.holder.ViewHolderCreator;
import com.sunday.shoufen.R;
import com.sunday.shoufen.adapter.AdHolder;
import com.sunday.shoufen.entity.Ad;
import com.sunday.shoufen.entity.IndexClassify;
import com.sunday.shoufen.http.ApiClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.shoufen.base.Constants.ACTIVE_BANNER;
import static com.sunday.shoufen.base.Constants.NEAR_BANNER;
import static java.io.FileDescriptor.in;

/**
 * Created by 刘涛 on 2017/10/19.
 */

public class BizDistrictDetailActivity extends BaseActivity {


    @Bind(R.id.banner)
    ConvenientBanner banner;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.toolbar_layout)
    CollapsingToolbarLayout toolbarLayout;
    @Bind(R.id.app_bar)
    AppBarLayout appbarLayout;
    @Bind(R.id.slide_tab)
    SlidingTabLayout tabLayout;
    @Bind(R.id.view_pager)
    ViewPager viewPager;
    @Bind(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    private boolean isRefresh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_district_detail);
        ButterKnife.bind(this);
        initRefresh();
        setUpToolBar();
        setUpCollapsingToolBar();
        getAds();

    }

    private void initRefresh(){
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                isRefresh=true;
                getAds();
            }
        });
    }

    private void setUpToolBar() {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    private void setUpCollapsingToolBar() {
        toolbarLayout.setContentScrimColor(ContextCompat.getColor(mContext,R.color.white));
        appbarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {
                    //collapseToolbar.setTitle("");
                    title.setText("");
                    toolbar.setNavigationIcon(R.mipmap.return_white);
                } else if (state == State.COLLAPSED) {
                    //collapseToolbar.setTitle("我的店铺");
                    title.setText("活动商铺");
                    toolbar.setNavigationIcon(R.mipmap.ic_back);
                } else {
                    //collapseToolbar.setTitle("");
                    title.setText("");
                    toolbar.setNavigationIcon(R.mipmap.return_white);
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.menu_shop, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }




    private List<String> titles = new ArrayList<>();
    private List<IndexClassify> dataSet = new ArrayList<>();
    private List<Ad> adList = new ArrayList<>();

    private void getAds() {
        Call<ResultDO<List<Ad>>> call = ApiClient.getApiAdapter().getAdsByCode(ACTIVE_BANNER);
        call.enqueue(new Callback<ResultDO<List<Ad>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Ad>>> call, Response<ResultDO<List<Ad>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                refreshLayout.finishRefresh();
                if (response.body().getCode() == 0) {
                    adList.clear();
                    adList.addAll(response.body().getResult());
                    updateBanner();
                    if (isRefresh){
                        ((ShopListFragment)fragments[viewPager.getCurrentItem()]).refresh();
                    }else {
                        getData();
                    }

                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Ad>>> call, Throwable t) {
                refreshLayout.finishRefresh();
            }
        });
    }


    private void updateBanner() {
        banner.startTurning(3000);
        final AdHolder indexAdHolder = new AdHolder();
        banner.setPages(new ViewHolderCreator<AdHolder>() {
            @Override
            public AdHolder createHolder() {
                return indexAdHolder;
            }
        }, adList)
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused});
        banner.notifyDataSetChanged();
    }

    private void getData() {
        Call<ResultDO<List<IndexClassify>>> call = ApiClient.getApiAdapter().getShopCats();
        call.enqueue(new Callback<ResultDO<List<IndexClassify>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<IndexClassify>>> call, Response<ResultDO<List<IndexClassify>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    titles.clear();
                    dataSet.clear();
                    dataSet.addAll(response.body().getResult());
                    if (!dataSet.isEmpty()) {
                        for (IndexClassify item : dataSet) {
                            titles.add(item.getName());
                        }
                        updateView();
                    }
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<IndexClassify>>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });

    }


    private void updateView() {

        initFragment();
    }

    private Fragment[] fragments;

    private void initFragment() {
        viewPager.setAdapter(new PagerAdapter(getSupportFragmentManager()));
        tabLayout.setViewPager(viewPager);
        viewPager.setCurrentItem(0, false);
        viewPager.setOffscreenPageLimit(titles.size());
    }

    public class PagerAdapter extends FragmentPagerAdapter {


        public PagerAdapter(FragmentManager fm) {
            super(fm);
            fragments = new Fragment[titles.size()];
        }

        @Override
        public Fragment getItem(int position) {
            if (fragments[position] == null) {
                fragments[position] = ShopListFragment.newInstance(dataSet.get(position).getId(),1);
            }
            return fragments[position];
        }

        @Override
        public int getCount() {
            return titles.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles.get(position);
        }
    }


}
